<?php
/**
 * Created by IntelliJ IDEA.
 * User: Jason
 * Date: 2018-12-04
 * Time: 15:14
 */

namespace app\member\controller;


use cmf\controller\AdminBaseController;
use think\Db;
use think\Exception;

/**
 * 订单控制器
 * Class AdminOrderController
 * @package app\member\controller
 */
class AdminOrderController extends AdminBaseController
{

    public function index()
    {
        $member_name = $this->request->param('member_name');
        $taobao_order_id = $this->request->param('taobao_order_id');

        $where = ['a.status'=>1000];
        if($member_name){
            $this->assign('member_name',$member_name);
            $where['member_name']=['like','%'.$member_name.'%'];
        }
        if($taobao_order_id){
            $this->assign('taobao_order_id',$taobao_order_id);
            $where['taobao_order_id']=['like','%'.$taobao_order_id.'%'];
        }
        $order = Db::name('member_order')->alias('a')
            ->join('member_member b','a.member_id=b.id')
            ->join('member_pack c','c.id=a.pack_id')
            ->where($where)
            ->field('a.*,b.member_name,b.taobao_id,c.pack_name')
            ->paginate(20);
        $this->assign('order',$order);
        return $this->fetch();
    }

    public function add()
    {
        $where=['status'=>1000];
        $pack = Db::name('member_pack')->where($where)->select();

        $member_id = $this->request->param('id');
        $member = Db::name('member_member')->where('id',$member_id)->find();
        $this->assign('pack',$pack);
        $this->assign('member',$member);
        return $this->fetch();
    }

    public function addPost()
    {
        $now = time();
        $param = $this->request->param();
        $param['status'] = 1000;
        $param['add_time'] = $now;
        $param['update_time'] = $now;
        echo "<pre>";
        print_r($param);
        Db::startTrans();
        try{
            $list = Db::name('member_pack')->alias('a')
                ->join('member_pack_item b','a.id=b.pack_id')
                ->where('b.pack_id',$param['pack_id'])
                ->field('b.item_id,b.number')
                ->select();

            Db::name('member_order')->insert($param);
            $order_id = Db::name('member_order')->getLastInsID();
            $data = [];
            for($i=1;$i<count($list);$i++){
                $data[] = [ 'order_id'=>$order_id,'item_id'=>$list[$i]['item_id'],'number'=>$list[$i]['number'],'status'=>1000,'add_time'=>$now,'update_time'=>$now];
            }
            Db::name('member_order_item')->insertAll($data);
            Db::commit();
        }catch(Exception $e){
            print_r($e);
            Db::rollback();
        }
    }

}